﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class EmptySquare : Actors 
{
	public List<EmptySquare> m_AdjacentSquare = new List<EmptySquare>();

	private bool m_IsHovering = false;
	private bool m_SomethingOver = false;
	private bool m_PlayerOver = false;
	private Vector3 m_InitialScale;
	private int m_ListID = 0;
	public int m_SquareValue = 0;
	
	public List<EmptySquare> AdjacentSquare {get { return m_AdjacentSquare; }}
	public bool IsHovering {get { return m_IsHovering; }}
	public bool SomethingOver {get { return m_SomethingOver; } set { m_SomethingOver = value;}}
	public bool PlayerOver {get { return m_PlayerOver; } set { m_PlayerOver = value;}}
	public Vector3 InitialScale {get { return m_InitialScale; }}
	public int ListID {get { return m_ListID; } set {m_ListID = value; }}
	public int SquareValue {get { return m_SquareValue; } set {m_SquareValue = value; }}

	private void Awake()
	{
		if(name != "Base")
		{
			m_ListID = (GamesManager.Instance.CurrentGame as TroubleGame).SquareListID;
			(GamesManager.Instance.CurrentGame as TroubleGame).SquareListID++;
			(GamesManager.Instance.CurrentGame as TroubleGame).AllSquares.Add (this);
		}
	}

	private void Start () 
	{
		m_InitialScale = aTransform.localScale;

		// Check Right
		Vector3 forward = aTransform.TransformDirection(Vector3.forward) * 10;
		Vector3 startPos = aTransform.position;
		startPos.x += transform.localScale.x;
		startPos.z -= transform.localScale.z/2;
				
		RaycastHit hit;

		for(int i = 0; i < 4; i++)
		{
			switch(i)
			{
			// Check Left
			case 1:
				startPos = aTransform.position;
				startPos.x -= transform.localScale.x;
				startPos.z -= transform.localScale.z/2;
				break;
			// Check Bottom
			case 2:
				startPos = aTransform.position;
				startPos.y -= transform.localScale.y;
				startPos.z -= transform.localScale.z/2;
				break;
			// Check Top
			case 3:
				startPos = aTransform.position;
				startPos.y += transform.localScale.y;
				startPos.z -= transform.localScale.z/2;
				break;
			}
			
			Ray ray = new Ray(startPos, forward);

			if(Physics.Raycast(ray, out hit, 1))
			{
				//if(gameObject.name == "Base")
				//{
					if(hit.collider.name != "Base")
					{
						m_AdjacentSquare.Add(hit.collider.GetComponent<EmptySquare>());
					}
				//}
				//else
				//{
				//	m_AdjacentSquare.Add(hit.collider.GetComponent<EmptySquare>());
				//}
			}
		}
	}
	
	void Update ()
	{
		if((GamesManager.Instance.CurrentGame as TroubleGame).MovesLeft <= 0)
		{
			m_IsHovering = false;
		}

		if(!m_IsHovering || (GamesManager.Instance.CurrentGame as TroubleGame).TurnEnded)
		{
			if(name != "Base")
			{
				aRenderer.material.color = Color.white;
				aTransform.localScale = m_InitialScale;
			}
		}
	}
	
	private void OnMouseEnter()
	{
		m_IsHovering = true;
	}

	private void OnMouseExit()
	{
		m_IsHovering = false;
	}
}
